package com.library.view;

import com.library.controller.BookController;
import com.library.entity.Pagination;
import com.library.entity.tableCol.BookCol;
import com.library.pojo.dto.book.BookPageQueryDTO;
import com.library.pojo.entity.LibraryBooks;
import com.library.result.PageResult;
import com.library.result.Result;
import com.library.utils.LocalCacheUtil;
import com.library.view.components.CommonButton;
import com.library.view.components.TipDialog;
import io.yukk1o.easytermui.EasyTermUI;
import io.yukk1o.easytermui.component.Button;
import io.yukk1o.easytermui.component.InputBox;
import io.yukk1o.easytermui.component.Panel;
import io.yukk1o.easytermui.component.Text;
import io.yukk1o.easytermui.component.complex.table.Table;
import io.yukk1o.easytermui.util.PrintUtils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;

/**
 * 图书列表面板
 *
 * 包含组件:
 * 顶部：返回按钮、多条件搜索输入框、是否可借选择框、搜索按钮
 * 中间：图书列表（默认10本，支持分页），显示图书id/书名/作者等信息及借阅按钮
 * 底部：页码显示（当前/最大）、上下页翻页按钮
 *
 * 交互流程:
 * 1. 默认加载前10本图书；
 * 2. 输入条件+选择可借状态→点击搜索→展示匹配结果；
 * 3. 翻页按钮切换页码查看更多；
 * 4. 点击借阅按钮执行借阅；
 * 5. 点击返回按钮回到上一级。
 */
public class BookPanel {
    private final BookController bookController = new BookController();
    private final EasyTermUI easyTermUI = new EasyTermUI();
    private final Panel rootPanel = new Panel(0, 0, 120, 40);
    private final Pagination pagination = new Pagination();
    private final BookPageQueryDTO bookPageQueryDTO = new BookPageQueryDTO();
    private final Table dataTable;
    private final Text pageText;

    private boolean init = false;


    public BookPanel() {
        pagination.setPageSize(25);


        /// 图书表格显示
        LinkedHashMap<String, Integer> colMeta = new LinkedHashMap<>();
        colMeta.put("编号", 8);
        colMeta.put("书名", 27);
        colMeta.put("作者", 20);
        colMeta.put("出版社", 29);
        colMeta.put("库存", 8);
        colMeta.put("可借", 8);
        colMeta.put("操作", 14);
        dataTable = new Table(0, 11, 25, colMeta);

        bookPageQueryDTO.setPageSize(pagination.getPageSize());


        ///         borrowPageQueryDTO.setPageNum(pageNum);
        ///         Result<PageResult> pageResultResult = borrowController.selectBorrowList(borrowPageQueryDTO);
        ///         PageResult pageResult = pageResultResult.getData();
        ///         List<BorrowCol> newBorrowCols = convertToBorrowCols(pageResult);
        ///         pagination.setTotal((int) pageResult.getTotal());
        ///         dataTable.setData(newBorrowCols);
        ///
        ///         if (init) {
        ///             dataTable.render();
        ///         }

        refresh(pagination.getCurrentPage());

        // 标题文本
        Text line1 = new Text(0, 1, 120, 1, "========================================================================================================================");
        Text title = new Text(57, 3, 5, 1, "图书馆系统");
        Text line2 = new Text(0, 5, 120, 1, "========================================================================================================================");

        //分隔线
        Text line3 = new Text(0, 10, 120, 1, "------------------------------------------------------------------------------------------------------------------------");
        rootPanel.addComponent(line3);
        rootPanel.addComponent(line1);
        rootPanel.addComponent(title);
        rootPanel.addComponent(line2);

        /// 返回按钮
        CommonButton backButton = new CommonButton(1, 3, " <<<< ", ( )-> {
            easyTermUI.stop();
        });
        rootPanel.addComponent(backButton);

        /// id输入框
        Text idText = new Text(3, 8, 3, 1, "ID:");
        InputBox idInput = new InputBox(7, 8, 6);
        rootPanel.addComponent(idText);
        rootPanel.addComponent(idInput);

        /// 书名输入框
        Text nameText = new Text(20, 8, 5, 1, "书名:");
        InputBox nameInput = new InputBox(26, 8, 20);
        rootPanel.addComponent(nameText);
        rootPanel.addComponent(nameInput);

        /// 作者输入框
        Text authorText = new Text(53, 8, 5, 1, "作者:");
        InputBox authorInput = new InputBox(58, 8, 10);
        rootPanel.addComponent(authorText);
        rootPanel.addComponent(authorInput);

        /// 出版社输入框
        Text publisherText = new Text(75, 8, 5, 1, "出版社:");
        InputBox publisherInput = new InputBox(80, 8, 20);
        rootPanel.addComponent(publisherText);
        rootPanel.addComponent(publisherInput);

        /// 搜索按钮
        Button searchButton = new Button(107, 8, " 搜索 ", (button -> {
            PrintUtils.printAt(1, 0, "值 " +  nameInput.getValue());
            bookPageQueryDTO.setPageNum(1);
            bookPageQueryDTO.setBookId(idInput.getValue() == null ? null :  Integer.valueOf(idInput.getValue()));            bookPageQueryDTO.setName(nameInput.getValue());
            bookPageQueryDTO.setAuthor(authorInput.getValue());
            bookPageQueryDTO.setPublisher(publisherInput.getValue());
            Result<PageResult> pageResult = bookController.pageQuery(bookPageQueryDTO);
            if (pageResult == null) {
                easyTermUI.mount(new TipDialog(40, 10, "搜索无结果"));
            }
            List<BookCol> newBookCols = getBookCols(pageResult);
            dataTable.setData(newBookCols);
            dataTable.render();
        }));

        /// 页码显示
        this.pageText = new Text(63, 39, 10, 1, getPageInfoText());
        rootPanel.addComponent(pageText);

        // 上下页翻页按钮
        Button prevButton = new Button(45, 39, " 上一页 ", (button) -> {
            if (pagination.prev()) {
                pageText.setText(getPageInfoText());
                refresh(pagination.getCurrentPage());
            }
        });

        rootPanel.addComponent(prevButton);
        Button nextButton = new Button(73, 39, " 下一页 ", (button -> {
            if (pagination.next()) {
                pageText.setText(getPageInfoText());
                refresh(pagination.getCurrentPage());
            }
        }));
        rootPanel.addComponent(nextButton);

        init = true;

        rootPanel.addComponent(searchButton);

        rootPanel.addComponent(dataTable);

        PrintUtils.clearScreen();
        easyTermUI.init(rootPanel);
    }

    private void refresh(int pageNum) {
        bookPageQueryDTO.setPageNum(pageNum);

        Result<PageResult> pageResultResult = bookController.pageQuery(bookPageQueryDTO);
        PageResult pageResult = pageResultResult.getData();

        pagination.setTotal((int) pageResult.getTotal());

        List<BookCol> bookCols = getBookCols(pageResultResult);

        dataTable.setData(bookCols);

        if (init) {
            dataTable.render();
            pageText.setText(getPageInfoText());
            pageText.render();
        }
    }

    private List<BookCol> getBookCols(Result<PageResult> pageResultResult) {
        List<LibraryBooks> records = pageResultResult.getData().getRecords();

        List<BookCol> bookCols = new ArrayList<>();


        for (LibraryBooks book : records) {

            BookCol col = new BookCol(book.getBookId(), book.getName(), book.getAuthor(), book.getPublisher(), book.getStock(), book.getLoan(), new Button(70, 0 ,"借阅", (button -> {
                BookController controller = new BookController();
                String result = "借阅失败";
                if (book.getLoan() <= 0) {
                    easyTermUI.mount(new TipDialog(40, 10, "库存不足"));
                }


                Result<String> stringResult = controller.borrowBook(book.getBookId(), Integer.valueOf(Objects.requireNonNull(LocalCacheUtil.readFromCache("userId"))));
                if (stringResult.getCode() == 1) {
                    result = "借阅成功,数据刷新需要一定时间";
                    pagination.setCurrentPage(1);
                }

                TipDialog tipDialog = new TipDialog(40, 10, result);
                easyTermUI.mountNoAutoStart(tipDialog);
                refresh(pagination.getCurrentPage());
                easyTermUI.start();
            })));

            bookCols.add(col);
        }
        return bookCols;
    }

    private String getPageInfoText() {
        return pagination.getCurrentPage() + " / " + pagination.getMaxPage();
    }

}